{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d6f0ab24-0dda-43bf-8136-93525a4d4b92",
   "metadata": {},
   "source": [
    "# Langsmit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1932e210-1058-4b53-931b-8aeb33bfad03",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -U langchain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "fab2649e-44e9-4756-a429-ffa4566f9cc0",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 准备，在环境变量中配置好下面4个参数\n",
    "# import os\n",
    "#\n",
    "# os.environ[\"LANGCHAIN_TRACING_V2\"]= \"true\"\n",
    "# os.environ[\"LANGCHAIN_ENDPOINT\"]= \"https://api.smith.langchain.com\"\n",
    "# os.environ[\"LANGCHAIN_API_KEY\"]= os.getenv(\"LANGCHAIN_API_KEY\")\n",
    "# os.environ[\"LANGCHAIN_PROJECT\"]=\"langchain-langsmith01\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "291ee157-65a2-4cb5-9ae8-be60b0a5ac49",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "AIMessage(content='你好!有什么可以帮助你的吗？', response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 10, 'total_tokens': 27}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_b28b39ffa8', 'finish_reason': 'stop', 'logprobs': None})"
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "llm = ChatOpenAI()\n",
    "llm.invoke(\"你好!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "873a0bf0-ff9e-4f88-8e89-2652ff023998",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f8c0386c-8b36-46c7-b0cb-a26498a5c907",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
      "\u001B[32;1m\u001B[1;3m\n",
      "Invoking: `tavily_search_results_json` with `{'query': \"current US president's wife's father\"}`\n",
      "\n",
      "\n",
      "\u001B[0m\u001B[36;1m\u001B[1;3m[{'url': 'https://en.wikipedia.org/wiki/Jill_Biden', 'content': 'By her own account, Biden was disappointed by his decision, believing her husband was highly qualified for the position, and \"would have been the best president\".[91]\\nBiden continued to teach at NOVA, handling a full load of five classes during the Fall 2015 semester.[92] During 2016, she was present with her husband on a listening tour for Cancer Moonshot 2020, an effort he was leading.[93] In March 2016, she headed the official party that welcomed American astronaut Scott Kelly back to Earth from his almost full year in space.[94]\\nSubsequent activities\\nThe former second couple launched the Biden Foundation in February 2017, with the purpose of allowing them to pursue the causes they cared most about, including focuses upon preventing violence against women, his moonshot initiative, and her interests in community colleges and military families.[96][30] That same month, she was named board chair of Save the Children; she said, \"I think [their] emphasis on education fits with my life\\'s work. In July 2022, Biden expressed frustration with the challenges her husband have faced as his administration has sought to address a range of issues.[153]\\nShe has played a role in the hiring of people within the administration\\'s press personnel and has criticized them when she felt they were not sufficiently protecting her husband\\'s image.[135][134]\\nBy October 2022, Biden had visited 40 U.S. states as first lady, outpacing the number of states that her husband visited during his presidency.[135][134]\\nForeign trips and activities\\nIn June 2021, Joe and Jill Biden visited Cornwall in the United Kingdom to attend the 47th G7 summit.[154] Biden and the Duchess of Cambridge visited primary school students and participated in a roundtable discussion focusing on early childhood education.[155] \"[141] (After many further negotiations, a significantly reduced bill passed Congress and became law as the Inflation Reduction Act of 2022, with free tuition for community college one of those provisions that did not make the cut.)[143]\\nJill Biden is an advocate for COVID-19 vaccination and toured the United States as a part of President Biden\\'s campaign to vaccinate Americans against COVID-19.[144]\\nIndeed, at times she was the foremost spokesperson in the administration for the vaccination effort; she was sent to parts of the country known for anti-vaccine beliefs and antipathy towards her husband, under the belief that she had a better chance of communicating with people in those areas.[145]\\nBiden, who was fully vaccinated with two booster shots, contracted COVID-19 herself in August 2022 and went into isolation protocols;[146] During the first year and a half of being first lady, a CNN poll revealed that Biden\\'s favorability ratings had declined, from 58 percent favorable to 28 percentage unfavorable at the time of her husband\\'s inauguration, compared to 34 percent favorable to 29 percent unfavorable during June–July 2022.[178]\\nA popularity dip of that extext was unusual, as first ladies usually have stronger ratings than their husbands do and stay high even when their husbands\\' ratings decline.[150]\\nThe decline has been attributed to Biden being more outwardly political than previous first ladies; to the general increase of partisan polarization in the United States dragging down everyone associated with an unpopular president; and, because of a large number of respondents shifting their views to \"no opinion\", an artifact of how the CNN poll was conducted.[150] she subsequently said \"thank God we all got off Zoom\".[133]\\nSecurity for her classes became tighter than it had been as second lady, with students having to go through a metal detector and initially getting a security briefing.[134]\\nShe has maintained her reputation as a tough grader who gave a lot of homework.[134]\\nFirst ladies are expected to have one or more causes that they advocate for, and Biden\\'s have been military families, education, and aspects of health care.[134]\\nThe same day may see her teaching classes at the college and then flying to an appearance as first lady.[135]\\nOf managing her professional life, her family roles, and her first lady activities all together, Biden has said, \"You can\\'t do anything in a haphazard way.'}]\u001B[0m\u001B[32;1m\u001B[1;3m\n",
      "Invoking: `tavily_search_results_json` with `{'query': 'Jill Biden father'}`\n",
      "responded: 很抱歉，我找不到相关信息。我将尝试使用其他方法来获取这个信息。\n",
      "\n",
      "\u001B[0m\u001B[36;1m\u001B[1;3m[{'url': 'https://en.wikipedia.org/wiki/Jill_Biden', 'content': 'By her own account, Biden was disappointed by his decision, believing her husband was highly qualified for the position, and \"would have been the best president\".[91]\\nBiden continued to teach at NOVA, handling a full load of five classes during the Fall 2015 semester.[92] During 2016, she was present with her husband on a listening tour for Cancer Moonshot 2020, an effort he was leading.[93] In March 2016, she headed the official party that welcomed American astronaut Scott Kelly back to Earth from his almost full year in space.[94]\\nSubsequent activities\\nThe former second couple launched the Biden Foundation in February 2017, with the purpose of allowing them to pursue the causes they cared most about, including focuses upon preventing violence against women, his moonshot initiative, and her interests in community colleges and military families.[96][30] That same month, she was named board chair of Save the Children; she said, \"I think [their] emphasis on education fits with my life\\'s work. In July 2022, Biden expressed frustration with the challenges her husband have faced as his administration has sought to address a range of issues.[153]\\nShe has played a role in the hiring of people within the administration\\'s press personnel and has criticized them when she felt they were not sufficiently protecting her husband\\'s image.[135][134]\\nBy October 2022, Biden had visited 40 U.S. states as first lady, outpacing the number of states that her husband visited during his presidency.[135][134]\\nForeign trips and activities\\nIn June 2021, Joe and Jill Biden visited Cornwall in the United Kingdom to attend the 47th G7 summit.[154] Biden and the Duchess of Cambridge visited primary school students and participated in a roundtable discussion focusing on early childhood education.[155] \"[141] (After many further negotiations, a significantly reduced bill passed Congress and became law as the Inflation Reduction Act of 2022, with free tuition for community college one of those provisions that did not make the cut.)[143]\\nJill Biden is an advocate for COVID-19 vaccination and toured the United States as a part of President Biden\\'s campaign to vaccinate Americans against COVID-19.[144]\\nIndeed, at times she was the foremost spokesperson in the administration for the vaccination effort; she was sent to parts of the country known for anti-vaccine beliefs and antipathy towards her husband, under the belief that she had a better chance of communicating with people in those areas.[145]\\nBiden, who was fully vaccinated with two booster shots, contracted COVID-19 herself in August 2022 and went into isolation protocols;[146] During the first year and a half of being first lady, a CNN poll revealed that Biden\\'s favorability ratings had declined, from 58 percent favorable to 28 percentage unfavorable at the time of her husband\\'s inauguration, compared to 34 percent favorable to 29 percent unfavorable during June–July 2022.[178]\\nA popularity dip of that extext was unusual, as first ladies usually have stronger ratings than their husbands do and stay high even when their husbands\\' ratings decline.[150]\\nThe decline has been attributed to Biden being more outwardly political than previous first ladies; to the general increase of partisan polarization in the United States dragging down everyone associated with an unpopular president; and, because of a large number of respondents shifting their views to \"no opinion\", an artifact of how the CNN poll was conducted.[150] she subsequently said \"thank God we all got off Zoom\".[133]\\nSecurity for her classes became tighter than it had been as second lady, with students having to go through a metal detector and initially getting a security briefing.[134]\\nShe has maintained her reputation as a tough grader who gave a lot of homework.[134]\\nFirst ladies are expected to have one or more causes that they advocate for, and Biden\\'s have been military families, education, and aspects of health care.[134]\\nThe same day may see her teaching classes at the college and then flying to an appearance as first lady.[135]\\nOf managing her professional life, her family roles, and her first lady activities all together, Biden has said, \"You can\\'t do anything in a haphazard way.'}]\u001B[0m\u001B[32;1m\u001B[1;3m根据我的搜索结果，美国现任总统的妻子是吉尔·拜登（Jill Biden），她的父亲是唐纳德·卡雅诺（Donald C. Jacobs）。\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": "{'input': '现任美国总统的妻子的父亲是?',\n 'output': '根据我的搜索结果，美国现任总统的妻子是吉尔·拜登（Jill Biden），她的父亲是唐纳德·卡雅诺（Donald C. Jacobs）。'}"
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# import os\n",
    "#\n",
    "# os.environ[\"LANGCHAIN_TRACING_V2\"]= \"true\"\n",
    "# os.environ[\"LANGCHAIN_ENDPOINT\"]= \"https://api.smith.langchain.com\"\n",
    "# os.environ[\"LANGCHAIN_API_KEY\"]= os.getenv(\"LANGCHAIN_API_KEY\")\n",
    "# os.environ[\"LANGCHAIN_PROJECT\"]=\"langchain-langsmith01\"\n",
    "\n",
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_openai_tools_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "#需要申请搜索引擎Tavily的API KEY\n",
    "tools = [TavilySearchResults(max_results=1,tavily_api_key= \"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\")]\n",
    "\n",
    "#拉取提示词模板\n",
    "prompt = hub.pull(\"hwchase17/openai-tools-agent\")\n",
    "\n",
    "# 配置LLM 模型\n",
    "llm = ChatOpenAI(model=\"gpt-3.5-turbo-1106\", temperature=0)\n",
    "\n",
    "# 构建Agent\n",
    "agent = create_openai_tools_agent(llm, tools, prompt)\n",
    "\n",
    "# 创建Agent 执行器、调用执行器\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "agent_executor.invoke({\"input\": \"现任美国总统的妻子的父亲是?\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48f5f001-838a-4458-b98f-9ac44bca1250",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
